package MonotonicStack2;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Stack;

/**
 * @author Lzm
 * @version 1.0
 */
public class nextGreaterElement_ {

  public int[] nextGreaterElement(int[] nums1, int[] nums2) {
    if (nums1.length == 0 || nums2.length == 0){
      return new int[0];
    }
    Stack<Integer> stack = new Stack<>();
    int[] result = new int[nums1.length];
    Arrays.fill(result,-1);

    HashMap<Integer,Integer> map = new HashMap<>();
    for (int i = 0; i < nums1.length; i++) {
      map.put(nums1[i],i);
    }

    for (int i = 0; i < nums2.length; i++) {
      while(!stack.isEmpty() && nums2[i] > nums2[stack.peek()]){
        if (map.containsKey(nums2[i])){
          result[stack.peek()] = nums2[i];
          stack.pop();
        }
        stack.push(i);
      }
    }
    return result;
  }
}
